/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import entity.Film;
import entity.Users;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 *
 * @author tiz
 */
public class Controller extends HttpServlet {

    //ham marshalling va unmarshalling
    //du lieu tu sql lay ve dung marshalling luu xuong xml
    //du lieu tu man hinh la xml qua server dung unmarshalling dua vao object luu vao sql
//    public static void unMar(Object obj, String url, String filename) {
//        try {
//            JAXBContext jc = JAXBContext.newInstance(url);
//            Unmarshaller us = jc.createUnmarshaller();
//            File f = new File(filename);
//            JAXBElement jax = (JAXBElement) us.unmarshal(f);
//            obj = (Object) jax.getValue();
//        } catch (JAXBException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public static void mar(Object obj, String filename) {
//        try {
//            JAXBContext jc = JAXBContext.newInstance(obj.getClass());
//            Marshaller mar = jc.createMarshaller();
//            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//            mar.marshal(obj, new File(filename));
//        } catch (JAXBException e) {
//            e.printStackTrace();
//        }
//    }
    //test servlet
    //
//    public static void main(String[] args){
//        String filmname = "f";
//        FilmsManager fm = new FilmsManager();
//        Films fList = new Films();
//        fList = fm.searchFilmsList(filmname);
//        mar(fList,"./web/XML/Films.xml");
//        Film film = new Film();
//        String url = "../web/XML";
//        String filename = "../web/XML/Films.xml";
//        unMar(film,url,filename);
//    }
    //test servlet
    private final String searchPage = "searchFilm.jsp";
    private final String homePage = "index.jsp";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, XMLStreamException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        String realPath = getServletContext().getRealPath("/");
        HttpSession session = request.getSession();
        try {
            if (action.equals("Login")) {
                String username = request.getParameter("txtusername");
                String password = request.getParameter("txtpassword");
                Users user = new Users();
                user = user.login(username, password);

                String url = searchPage;

                if (user != null) {
                    
                    session.setAttribute("currentUser", user.getUserID());
                    session.setAttribute("currentRole", user.getUserRole());
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.include(request, response);
            } else if (action.equals("Search film")) {
                String searchFilm = request.getParameter("searchFilm");
                XMLInputFactory xif = XMLInputFactory.newInstance();
                String filePath = getServletContext().getRealPath("/")
                        + "xml\\Films.xml";
                XMLStreamReader xsr = xif.createXMLStreamReader(filePath,
                        new FileInputStream(filePath));
                int eventType = xsr.getEventType();

                String filmID = null;
                String fName = null;
                BigDecimal budget = null;
                String releaseDate = null;
                String directorName = null;
                String filmDescription = null;
                String filmUrl = null;
                ArrayList list = new ArrayList();
                boolean found = false;

                while (xsr.hasNext()) {
                    eventType = xsr.next();
                    if (eventType == XMLStreamConstants.START_ELEMENT) {
                        if (xsr.getLocalName().equals("FilmID")) {
                            eventType = xsr.next();
                            filmID = xsr.getText().trim();
                        } else if (xsr.getLocalName().equals("Name")) {
                            eventType = xsr.next();
                            fName = xsr.getText().trim();
                            if(fName.trim().indexOf(searchFilm)> -1){
                                found = true;
                            }
                        }else if (found && xsr.getLocalName().equals("Budget")) {
                            eventType = xsr.next();
                            budget = new BigDecimal( xsr.getText().trim());
                        }else if (found && xsr.getLocalName().equals("ReleaseDate")) {
                            eventType = xsr.next();
                            releaseDate = xsr.getText().trim();
                        }else if (found && xsr.getLocalName().equals("DirectorName")) {
                            eventType = xsr.next();
                            directorName = xsr.getText().trim();
                        }else if (found && xsr.getLocalName().equals("FilmDescription")) {
                            eventType = xsr.next();
                            filmDescription = xsr.getText().trim();
                        }else if (found && xsr.getLocalName().equals("TrailerUrl")) {
                            eventType = xsr.next();
                            filmUrl = xsr.getText().trim();
                            Film film = new Film(filmID, fName, budget, releaseDate, directorName, filmDescription, filmUrl);
                            found = false;
                            list.add(film);
                        }
                    }
                }

                session.setAttribute("searchFilmList", list);

                RequestDispatcher rd = request.getRequestDispatcher(searchPage);
                rd.include(request, response);
            } else if (action.equals("Register")) {
                String txtuserid = request.getParameter("txtuserid");
                String txtpassword = request.getParameter("txtpassword");
                String txtbirthday = request.getParameter("txtbirthday");
                String txtaddress = request.getParameter("txtaddress");
                String txtphone = request.getParameter("txtphone");
            } else if (action.equals("Add film")) {
            }
        } catch(Exception e){
            e.printStackTrace();
        }
        finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (XMLStreamException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (XMLStreamException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
